#-*- coding: UTF-8 -*-
import datetime
import re
import socket
import os
import io
import requests

# 目标: 监控最近20分钟内的错误日志

##监控时间
#现在时间
now = datetime.datetime.now()
mon_time = now.strftime("%Y-%m-%d %H:%M:%S")

##获取20 分钟前的时间
twenty_minutes_ago = now - datetime.timedelta(minutes=20)

##获取本机ip
def get_ip_address():
    try:
        # 获取本地主机名
        hostname = socket.gethostname()
        # 获取本地IP
        ip_address = socket.gethostbyname(hostname)
        return ip_address
    except Exception as e:
        ip_address = 'UNKOWN'
        return ip_address
ip = get_ip_address()

##获取要监控的log
dir_pattern = re.compile(r'\d{4}-\d{2}-\d{2}')
def find_files(path, all_files):
    file_list = os.listdir(path)
    for file in file_list:
        cur_path = os.path.join(path, file)
        if os.path.isdir(cur_path):
            if dir_pattern.search(file):
                continue
            else:
                find_files(cur_path, all_files)
        else:
            if re.search(r'(.log)$',file):
                all_files.append(cur_path)
    return all_files
#指定log目录
#path = '/root/liweikang/logtest'
#path = '/Users/liwk/py/oratk_web/oratk'
path = '/opt/canal_deploy/logs'
#指定log文件-list
all_log_files = []
find_files(path,all_log_files)
#print(all_log_files)

##
w_tab_url='http://dba.corp.shiqiao.com/face.html?faceid=i6gkoi2l7sr8j1fhbtqc0u9apx&token=a9ebv8k24n6pli'

##
event_info = 'canal集群日志中存在错误'
err_pattern = re.compile(r'ERROR')
dataformate_pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})')
for file in all_log_files:
    list_rpt_error = []
    #print(file)
    with io.open(file, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            if dataformate_pattern.search(line):
                timestamp_date_str, timestamp_time_str = line.split()[:2]
                log_date = timestamp_date_str + ' ' + timestamp_time_str
                log_date_fm = datetime.datetime.strptime(log_date, '%Y-%m-%d %H:%M:%S.%f')
                if twenty_minutes_ago <= log_date_fm <= now and err_pattern.search(line):
                    list_rpt_error.append(line.rstrip())
        f.close()
    if len(list_rpt_error) > 0:
        error_line_1 = list_rpt_error[0]
        if len(list_rpt_error) <2:
            error_line_2 = ''
            out_line = ''
        else:
            error_line_2 = list_rpt_error[1]
            out_line = '(只显示前两条报错信息)'
        topic = file.split('/')[-2]
        rpt_error_info = '''**报警事件: %s**
- 报警时间: %s
- IP: %s
- InstanceName: %s
- 报错信息: %s
-       %s
-       %s'''%(event_info,mon_time,ip,topic,out_line,error_line_1,error_line_2)
        #print(rpt_error_info)
        url_params = {
            'ip_info':ip,
            'event_info':event_info,
            'log_info':rpt_error_info,
            'file_path':file,
            'topic':topic
        }
        print(rpt_error_info)
        requests.get(w_tab_url, params=url_params)